

import imp
import requests
import json
import datetime
import random
import time
import threading
import execjs

class getTongHuaShunData(threading.Thread):
    def __init__(self,strategyName,cookie,recordTxtName):
        threading.Thread.__init__(self)
        self.strategyName = strategyName
        self.cookie = cookie
        self.recordTxtName = recordTxtName
        
    def run(self):
          ############### 变量设置
        dailyUpUrl = dailyUp_pro
        tongHuaShunV = self.cookie  
        ###############
        record = open(self.recordTxtName,'w',encoding='utf-8')
        todayDate = datetime.datetime.now().strftime("%Y-%m-%d 00:00:00")

        uploadJson = {}
        uploadJson['uploadDate'] = todayDate
        uploadData = []

        f = open(self.strategyName,encoding="utf-8")
        
        for line in f.readlines():
            if line != '':
                sleepTIme = random.randint(5,10)
                arr = line.split(' ')
                strategyId = int(arr[0])
                strategyName = arr[1].replace('\n','')

                ## 返回的就是 股票代码
                stockCodes = getDatasFromTongHua(strategyName=strategyName,record = record,tongHuaShunV = tongHuaShunV,strategyId =strategyId )
                ## 拼接成可用的对象信息
                stockInfos = {"strategyId":strategyId,"stockCodes":stockCodes}
                uploadData.append(stockInfos)
                # 程序睡眠一段时间, 防止
                time.sleep(sleepTIme)

        f.close()
        uploadJson['data'] = uploadData
        jsonBoday = json.dumps(uploadJson)
        record.write(jsonBoday)
        dailyUpResponse = requests.request("POST", dailyUpUrl, headers=dailyUp_headers, data=jsonBoday)
        print(self.recordTxtName + '---' + dailyUpResponse.text)
        record.write('\n')
        record.write(dailyUpResponse.text)
        record.close()


## dailyUp数据
dailyUp_dev = "https://engraveshine.cn/dev/dailyup/daily/stock/upload"
dailyUp_pro = "https://engraveshine.cn/dailyup/daily/stock/upload"



dailyUp_headers = {
    'adminToken': 'dingguanghui888',
     'Content-Type': 'application/json'
}


payload = {
    "question": '布林中轨突破;沪深A股;上市大于300天;基金持仓比例>3%;放量',
    "page": 1,
    "perpage": 100,
    "log_info": '{"input_type": "typewrite"}',
    "source": "Ths_iwencai_Xuangu",
    "version": 2.0,
    "secondary_intent": "",
    "query_area": "",
    "block_list": "",
    "add_info": '{"urp": {"scene": 1, "company": 1, "business": 1}, "contentType": "json", "searchInfo": true}'
}

headers = {
    "Accept": "application/json,text/javascript,*/*;q=0.01",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "zh-CN,zh;q=0.8",
    'Connection': 'keep-alive',
    'Content-Type': "application/x-www-form-urlencoded; charset=UTF-8",
    'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
    'X-Requested-With': "XMLHttpRequest"
}



def getDatasFromTongHua(strategyName,record,tongHuaShunV,strategyId ):
    payload['question'] = strategyName
    # rs 是个列表
    rs = []
    headers['hexin-v'] = tongHuaShunV

    # request 网络请求
    response = requests.post('http://www.iwencai.com/unifiedwap/unified-wap/v2/result/get-robot-data', data=payload, headers=headers)

    print(strategyName + '-------' + str(response.status_code))
    if response.status_code != 200:
        record.write(str(strategyId) + ' ' +strategyName)
        record.write(str(response.status_code) + '----' + response.text)
        record.write('\n')
    else:
        # 如果 code = 200 请求正常, 通过json.loads , 把返回的数据, 转换成json对象
        try:
            c = response.json()['data']['answer'][0]['txt'][0]['content']['components'][0]['data']['datas']
            print(strategyName + '---数据长度---:',str(len(c)),'\n')
            for i in c:
                # rs.append('"' + i[0][0:6] + '"')
                # 把返回值取出来, 加到结果列表里面
                rs.append(i['code'])
        except Exception as ex:
            print(strategyName + '---exception---' + str(ex))
            print(strategyName + '---response---' + response.json())
    return rs

# 程序入口
if __name__ == "__main__":
    # 循环token
    for i in range(1,4):
    #  for i in range(2,3):
        strategyName = 'strategy' + str(i) + '.txt'
        recordTxt = 'record' + str(i) + '.txt'
        t = getTongHuaShunData(strategyName,execjs.compile(open('hexin.js','r').read()).call('v'),recordTxt)
        t.start()
        
  